package ch02sl.jd.jd1;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.net.MalformedURLException;
import java.util.Iterator;

public class XMLParseUpd {

    public  void showPhoneInfo() {
        Document doc = null;
        try {
            SAXReader saxReader = new SAXReader();
            doc =  saxReader.read(new File("src/test/java/ch02sl/sz/PhoneInfo.xml"));
        }
         catch (DocumentException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        Element root =  doc.getRootElement();
        for (Iterator<Element> it = root.elementIterator("student"); it.hasNext(); ) {
            Element brand = it.next();
            // 获取Brand的属性值
            String brandName = brand.attributeValue("id");
            String score = brand.attributeValue("score");
            if ("3".equals(brandName)) {
                brand.setAttributeValue("score", "60");
            }

        }

        // 保存修改后的XML文件
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        try {
            XMLWriter writer = new XMLWriter(new FileWriter("src/test/java/ch02sl/jd/Student.XML"), format);
            writer.write(doc);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        XMLParseUpd parse = new XMLParseUpd();
        parse.showPhoneInfo();
    }
}
